using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SQLite;
using DesktopWidgetApp.Shared;

namespace DesktopWidgetApp.Core.Data
{
    /// <summary>
    /// SQLite仓储基类
    /// </summary>
    /// <typeparam name="TEntity">实体类型</typeparam>
    public abstract class SqliteRepositoryBase<TEntity> : IRepository<TEntity>
        where TEntity : class, new()
    {
        protected readonly SQLiteAsyncConnection _database;
        protected readonly string _tableName;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="databasePath">数据库路径</param>
        protected SqliteRepositoryBase(string databasePath)
        {
            _database = new SQLiteAsyncConnection(databasePath);
            _tableName = typeof(TEntity).Name;
            _database.CreateTableAsync<TEntity>().Wait();
        }

        /// <summary>
        /// 获取所有实体
        /// </summary>
        /// <returns>实体列表</returns>
        public async Task<IEnumerable<TEntity>> GetAllAsync()
        {
            return await _database.Table<TEntity>().ToListAsync();
        }

        /// <summary>
        /// 根据主键获取实体
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>实体</returns>
        public async Task<TEntity> GetByIdAsync(Guid id)
        {
            return await _database.FindAsync<TEntity>(id);
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>添加后的实体</returns>
        public async Task<TEntity> AddAsync(TEntity entity)
        {
            await _database.InsertAsync(entity);
            return entity;
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns>更新后的实体</returns>
        public async Task<TEntity> UpdateAsync(TEntity entity)
        {
            await _database.UpdateAsync(entity);
            return entity;
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns>是否删除成功</returns>
        public async Task<bool> DeleteAsync(Guid id)
        {
            var count = await _database.DeleteAsync<TEntity>(id);
            return count > 0;
        }

        /// <summary>
        /// 根据条件查询实体
        /// </summary>
        /// <param name="predicate">查询条件</param>
        /// <returns>符合条件的实体列表</returns>
        public async Task<IEnumerable<TEntity>> FindAsync(Func<TEntity, bool> predicate)
        {
            var allItems = await GetAllAsync();
            return allItems.Where(predicate);
        }
    }
}